/* Made by Sam Jordan */
#include <iostream>
#include <tinyxml/tinyxml.h>
#include <gtk/gtk.h>
#include <curl/curl.h>
#include <string>
#include <fstream>
#include <time.h>
#include "convert.h"
using namespace std;

// Put the libcurl errors here
static char errorBuffer[CURL_ERROR_SIZE];

// Make the buffer content go in this string
static string buffer;

// Function Prototypes
void showInfo();

// Wierd writer thingy
static int writer(char *data, size_t size, size_t nmemb, std::string *buffer)
{
	int result = 0;
	
	if (buffer != NULL)
	{
		buffer->append(data, size*nmemb);
		result = size*nmemb;
	}
	return result;
}

int main(int argc, char *argv[])
{
	// Run info function (@ bottom of file)
	showInfo();
	
	// Set the strings to hold the settings in
	string userID, apiKey, charID, urlData;
	
	// Load the settings file
	TiXmlDocument settin("settings.xml");
	
	// Check to see if it loaded
	bool loadOkay = settin.LoadFile();
	if (loadOkay)
	{
		printf("~ Settings File Loaded\n\n");
	} else {
		printf("~ Settings File Failed to Load!\n\n");
	}
	
	// Navigate to the first element of the file
	TiXmlElement *pSettings = settin.FirstChildElement();
	
	// Set the userID
	userID = pSettings->GetText();
	
	// Go to the next element
	pSettings = pSettings->NextSiblingElement();
	
	// Set the apiKey
	apiKey = pSettings->GetText();
	
	// Go to the next Element
	pSettings = pSettings->NextSiblingElement();
	
	// Set the charID
	charID = pSettings->GetText();
	
	// A very nasty way to stick the string together, but I dont know how to otherwize :)
	urlData = "http://api.eve-online.com/char/SkillInTraining.xml.aspx?userID=";
	urlData += userID;
	urlData += "&apiKey=";
	urlData += apiKey;
	urlData += "&characterID=";
	urlData += charID;
	
	// Make the libcurl objects
	CURL *curl;
	CURLcode result;
	
	
	// Make the curl handle
	curl = curl_easy_init();
	
	// Check if curl handle worked properly and do everything
	if (curl)
	{
		// Set curl options
		curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
		curl_easy_setopt(curl, CURLOPT_URL, urlData.c_str());
		curl_easy_setopt(curl, CURLOPT_HEADER, 0);
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
		
		// Actually get the page
		result = curl_easy_perform(curl);
		
		// Clean up!
		curl_easy_cleanup(curl);
		
		// If it downloaded the file
		if (result == CURLE_OK)
		{
			// Give message
			cout << "~ Sucessfully downloaded the XML file.\n";
			
			// Make a new fileHandle
			ofstream fileHandle;
			
			// Open/Create data.xml, delete all content and prepare it for writing
			fileHandle.open("data.xml", ios::out | ios::out | ios::trunc);
			
			// Write the contents of 'buffer' into the file
			fileHandle << buffer;
			
			// Message
			cout << "~ Written data to 'data.xml'.\n";
			
			// Close the file
			fileHandle.close();
			
			// Now to open the xml file and read it!
			TiXmlDocument doc("data.xml");
			
			// Check to see if it loaded
			bool loadOkay = doc.LoadFile();
			if (loadOkay)
			{
				printf("~ XML File Loaded\n");
			} else {
				printf("~ XML File Failed to Load!\n");
			}
			
			// Navigate to the first element of the XML document
			TiXmlElement *pElement = doc.FirstChildElement();
			
			// Go down another level
			TiXmlElement *pNew = pElement->FirstChildElement();
			
			// Move to the next element in that level (result)
			pNew = pNew->NextSiblingElement();
			
			// Finally make a pointer to show off our shiny new thingy and move to the skill finished time
			TiXmlElement *pDest = pNew->FirstChildElement();
			
			// Data extraction
			// Now here comes the very messy date calculations
			//Set longs for the year, month, day etc and the Epoch time in seconds
			long cYear, cMonth, cDay, cHour, cMin, cSec, cEpoch;
			
			// Set a time structure to store the time data in
			struct tm tm;
            char buf[255];

			// Extract the different parts of the date
            strptime(pDest->GetText(), "%Y-%m-%d %H:%M:%S", &tm);
            strftime(buf, sizeof(buf), "%Y", &tm);
            cYear = convertToLong(buf);
            strftime(buf, sizeof(buf), "%m", &tm);
            cMonth = convertToLong(buf);
            strftime(buf, sizeof(buf), "%d", &tm);
            cDay = convertToLong(buf);
            strftime(buf, sizeof(buf), "%H", &tm);
            cHour = convertToLong(buf);
            strftime(buf, sizeof(buf), "%M", &tm);
            cMin = convertToLong(buf);
            strftime(buf, sizeof(buf), "%S", &tm);
            cSec = convertToLong(buf);
            
            cEpoch = mktime(&tm);
            
			pDest = pDest->NextSiblingElement();
			
			// Now here comes the very messy date calculations
			long fYear, fMonth, fDay, fHour, fMin, fSec, fEpoch;

            strptime(pDest->GetText(), "%Y-%m-%d %H:%M:%S", &tm);
            strftime(buf, sizeof(buf), "%Y", &tm);
            fYear = convertToLong(buf);
            strftime(buf, sizeof(buf), "%m", &tm);
            fMonth = convertToLong(buf);
            strftime(buf, sizeof(buf), "%d", &tm);
            fDay = convertToLong(buf);
            strftime(buf, sizeof(buf), "%H", &tm);
            fHour = convertToLong(buf);
            strftime(buf, sizeof(buf), "%M", &tm);
            fMin = convertToLong(buf);
            strftime(buf, sizeof(buf), "%S", &tm);
            fSec = convertToLong(buf);
            
            fEpoch = mktime(&tm);
            
            // Work out the difference between the 2 dates in seconds
            long difference = fEpoch - cEpoch;
            long sec, min, hour, day;
            
            // Work out the amound ot days, hours, mins and seconds!
            day = difference/60/60/24;
            hour = (difference-(86400*day))/60/60;
            min = ((difference-(86400*day))-(3600*hour))/60;
            sec = ((difference-(86400*day))-(3600*hour))-(60*min);
            
            // Display them!
            cout << "\nDays till skill finishes: " << day;
            cout << "\nHours till skill finishes: " << hour;
            cout << "\nMinutes till skill finishes: " << min;
            cout << "\nSeconds till skill finishes: " << sec;
			cout << "\n\nYour skill finishes at: " << pDest->GetText() << endl << endl;
			
			
			
		}
	}

	return 0;
	
}

// A function to show the info... the prototype is @ the top
void showInfo()
{
	cout << "\nLinuxmon Version 0.02 alpha\n"
		<< "Written By Sam Jordan\n"
		<< "www.samjordan.co.uk\n\n";
}
